import { Controller } from 'egg';
import { UserRole } from '../model/user';

const UPDATE_TAEACHER_SCHEDULES_VALIDATION = {
    schedules: {
        type: 'array',
        itemType: 'object',
        rule: {
            day: 'int',
            time_spans: {
                type: 'array',
                itemType: 'object',
                rule: {
                    time_from: {
                        type: 'string',
                        required: true,
                        // format: /^\d{2}:\d{2}$/,
                    },
                    time_to: {
                        type: 'string',
                        required: true,
                        // format: /^\d{2}:\d{2}$/,
                    },
                },
            },
        },
    },
};

export default class TeacherScheduleController extends Controller {
    /**
     * 返回老师排期
     */
    public async getTeacherSchedules() {
        const { ctx, service } = this;
        let teacherId: number|undefined;
        if (ctx.user.role === UserRole.Student) {
            teacherId = ctx.user.teacher_id;
        } else if (ctx.user.role === UserRole.Teacher) {
            teacherId = ctx.user.id;
        }

        if (!teacherId) {
            // 请求异常
            return ctx.helper.fail(ctx);
        }
        const teacherSchedules = await service.teacherSchedule.getTeacherSchedules(teacherId);
        return ctx.helper.success(ctx, teacherSchedules);
    }

    /**
     * 老师更新自己的排期
     */
    public async updateTeacherSchedules() {
        const { ctx, service } = this;
        if (ctx.user.role !== UserRole.Teacher) {
            ctx.helper.fail(ctx);
        }
        ctx.validate(UPDATE_TAEACHER_SCHEDULES_VALIDATION);
        // 检查老师排课时间是否有重合
        const schedules = ctx.request.body.schedules;
        for (const schedule of schedules) {
            if (schedule.time_spans) {
                for (let i = 0; i < schedule.time_spans.length - 1; ++i) {
                    for (let j = i + 1; j < schedule.time_spans.length; ++j) {
                        const ts1 = schedule.time_spans[i];
                        const ts2 = schedule.time_spans[j];
                        if (!(ts1.time_from < ts2.time_from && ts1.time_to <= ts2.time_from) &&
                            !(ts1.time_from >= ts2.time_to && ts1.time_to > ts2.time_to)) {
                            ctx.helper.invalidateParamsError();
                        }
                    }
                }
            }
        }
        await service.teacherSchedule.updateTeacherSchedules(schedules, ctx.user.id);
        return ctx.helper.success(ctx);
    }
}
